from flask import Blueprint, jsonify, request
from flask_pymongo import PyMongo
from config.config import MongoConfig  # 需要在配置文件中添加MongoDB配置
from functools import wraps
from dataclasses import dataclass, asdict
from typing import Optional

# 定义mongodb蓝图
mongodb_bp = Blueprint('mongodb', __name__)

# 初始化MongoDB
mongo = PyMongo()

# mongodb的启动方式：mongod --dbpath D:\app\mongodb-windows-x86_64-5.0.26\mongodb-win32-x86_64-windows-5.0.26\db
# MongoDB初始化函数
def init_mongo(state):
    app = state.app
    app.config['MONGO_URI'] = MongoConfig.MONGO_URI
    print(f"MONGO_URI: {app.config['MONGO_URI']}")
    mongo.init_app(app)

# 注册初始化函数
mongodb_bp.record(init_mongo)

# 统一接口异常处理装饰器
def handle_db_exceptions(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except Exception as e:
            return jsonify({'status': 'error', 'message': str(e)})
    return decorated_function

# 获取用户列表
@mongodb_bp.route('/getUserList', methods=['GET'])
@handle_db_exceptions
def get_user_list():
    users = mongo.db.users.find({}, {'_id': 0})  # 不返回_id字段
    return jsonify({
        'status': 'success',
        'data': list(users)
    })

# 定义User数据类
@dataclass
class User:
    user_id: str
    username: str
    email: str
    age: Optional[int] = None
    phone: Optional[str] = None

    def to_dict(self):
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict):
        return cls(**data)
    
# 添加用户
@mongodb_bp.route('/addUser', methods=['POST'])
@handle_db_exceptions
def add_user():
    user_data = request.get_json()
    user = User.from_dict(user_data)
    mongo.db.users.insert_one(user.to_dict())
    return jsonify({
        'status': 'success',
        'message': '添加成功'
    })

# 更新用户信息
@mongodb_bp.route('/updateUser/<string:user_id>', methods=['PUT'])
@handle_db_exceptions
def update_user(user_id):
    user_data = request.get_json()
    user = User.from_dict(user_data)
    mongo.db.users.update_one(
        {'user_id': user_id},
        {'$set': user.to_dict()}
    )
    return jsonify({
        'status': 'success',
        'message': '更新成功'
    })

# 删除用户
@mongodb_bp.route('/deleteUser/<string:user_id>', methods=['DELETE'])
@handle_db_exceptions
def delete_user(user_id):
    mongo.db.users.delete_one({'user_id': user_id})
    return jsonify({
        'status': 'success',
        'message': '删除成功'
    })
